﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using SDT.Lib.Paging;
using SDT.Lib.Common;
using System.IO;
using SDT.Lib.Helpers;
using SDT.Admin.Properties;
using SDT.Model;
using SDT.Admin.ViewModels;

namespace iSTM.Admin.Controllers
{
	[RoleHelper(Roles = RoleSystem.Article)]
    public class ArticleController : Controller
    {
        /// <summary>
        /// Created by: Vietlv
        /// Created date: 06/07/2011
        /// Description: Manage Articles - Class Article controler;
        /// </summary>

        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /Article/ Index(int? Page)
        public ActionResult Index(int? page)
        {
            try
            {
                var action = Request["hdAction"];
                if (action != null && (action == "delete"))
                {
                    try
                    {
                        foreach (string key in Request.Form)
                        {
                            var checkbox = String.Empty;
                            if (key.StartsWith("chk"))
                            {
                                checkbox = Request.Form["" + key];

                                if (checkbox != "false")
                                {
                                    int strId = Utils.ParseInt(key.Substring(4));
                                    if (strId > 0)
                                    {
                                        var docRootPath = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath;
                                        var imgRootPath = Settings.Default.SiteRootPath + Settings.Default.ArticleImageRootPath;
                                        ArticleManager.Delete(strId, imgRootPath, docRootPath);
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception exp)
                    {
                        ViewData[Messages.MessageInfo] = exp.Message;
                        return View();
                    }
                }
                if (page == null) page = 1;
                string order = UserState.getUserStateFromRequest("article.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("article.orderDir", "orderDir", "desc").ToString();
                int catID = Convert.ToInt32(UserState.getUserStateFromRequest("article.CatID", "CatID", 0));
                int currentHot = Convert.ToInt32(UserState.getUserStateFromRequest("article.HotStatus", "HotStatus", 0));
                int currentPub = Convert.ToInt32(UserState.getUserStateFromRequest("article.PubStatus", "PubStatus", 0));
                string keyword = UserState.getUserStateFromRequest("article.Keyword", "Keyword", "").ToString();
                keyword = keyword.Trim();
                int pageSize = int.Parse(UserState.getUserStateFromRequest("article.pageSize", "PageSize", 20).ToString());

                var arrc = catID > 0 ? ArticleManager.GetChild(catID) : new List<int>();
                var articles = eDataContext.Articles
                    .Where(a => (catID > 0 ? arrc.ToArray().Contains(a.CatID.Value) : true))
                    .Where(a => currentHot > 0 ? a.HotYN == (currentHot == 1 ? true : false) : true)
                    .Where(a => currentPub > 0 ? a.PubYN == (currentPub == 1 ? true : false) : true)
                    .Where(a => (string.IsNullOrEmpty(keyword) ? true :
                        (a.Title.ToLower().Contains(keyword.ToLower()) ||
                        a.Summary.ToLower().Contains(keyword.ToLower()) ||
                        a.ArticleContent.Contains(keyword)
                        )))
                    .OrderBy(string.Format("{0} {1}", order, orderDir))
                    .ToPagedList(page.Value - 1, pageSize);

                var articleCategory = ArticleManager.GetListCategory();
                var hosts = Utils.StringToDictionary(Settings.Default.ArticleHotStatus.ToString(), ",");
                var pubs = Utils.StringToDictionary(Settings.Default.ArticlePubStatus.ToString(), ",");

                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;

                return View(new ArticleIndexViewModel
                {
                    Articles = articles,
                    Categories = articleCategory,
                    HotStatus = hosts,
                    PubStatus = pubs,
                    CurrentCat = catID,
                    CurrentHotStatus = currentHot,
                    CurrentPubStatus = currentPub,
                    Keyword = keyword,
                    ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Article/Details(int id)
        public ActionResult Details(int id)
        {
            var currentEventid = eDataContext.ArticleEventMaps.Where(e => e.ArticleID == id).SingleOrDefault();
            var currentCompanyid = eDataContext.ArticleCompanyMaps.Where(e => e.ArticleID == id).SingleOrDefault();

            var cp = currentCompanyid == null ? null : eDataContext.Companies.Where(e => e.ID == currentCompanyid.CompanyID).SingleOrDefault();
            var ce = currentEventid == null ? null : eDataContext.Events.Where(e => e.ID == currentEventid.EventID).SingleOrDefault();
            
            var article = eDataContext.Articles.Where(a => a.ID == id).SingleOrDefault();
            // product image
            List<string> listF = article.AddDate != null ? Uploads.GetFile(id, Settings.Default.SiteRootPath, Settings.Default.DocumentInArticleRootPath, Settings.Default.DocumentInArticleFomatSubPath, article.AddDate) : null; // Modified by Vietlv (isert confident pro.AddDate = null)
            var imgRootUrl = Settings.Default.SiteRootUrl + Settings.Default.ArtileImagePreviewUrlPrefix;
            var listTagID = eDataContext.ArticleTagMaps.Where(e => e.ArticleID == id).Select(e => e.TagID).ToList();
            var listTag = eDataContext.Tags.ToList();
            var listDocumentID = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).Select(e => e.DocumentID).ToList();
            var listDocuemt = eDataContext.Documents.ToList();
            return View(new ArticleEditViewModel() {
                Article = article,
                CurrentCompany = cp,
                CurrentEvent = ce,

                ImageRootUrl = imgRootUrl,
                FileRootURL = Settings.Default.SiteRootUrl + Settings.Default.DocumentInArticlePreviewUrl,
                ListFile = listF,
                ListTagID = listTagID,
                Tags = listTag,
                ListDocumentID = listDocumentID,
                Documents =listDocuemt
            });
        }
        #endregion

        #region GET: /Article/Create

        public ActionResult Create()
        {
            var categories = ArticleManager.GetListCategory();            
            var company = eDataContext.Companies.ToList();
            var events = eDataContext.Events.ToList();
            return View(new ArticleEditViewModel()
            {
                Categories = categories,
                Companys = company,
                Events = events                
            });
        }
        #endregion

        #region POST: /Article/Create
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(ArticleEditViewModel a)
        {
            try
            {
                // Modified by Vietlv (04/08/2011)
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open(); //Vietlv
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();                                   //Vietlv               
                // TODO: Add insert logic here
                UpdateModel(a);
                a.Article.CatID = Request["CatID"] != string.Empty ? Utils.ParseInt(Request["CatID"]) : (int?)null;
                a.Article.PubYN = Request["PublishYN"] != "false" ? true : false;
                a.Article.HotYN = Request["HotYN"] != "false" ? true : false;
                a.Article.AddDate = DateTime.Now;
                a.Article.AddBy = UserManager.GetUserId();
                
                if (a.Article.MetaKeyword == null || a.Article.MetaKeyword == string.Empty) a.Article.MetaKeyword = a.Article.Title;
                if (a.Article.MetaDescription == null || a.Article.MetaDescription == string.Empty) a.Article.MetaDescription = a.Article.Title;
                if (a.Article.MetaTag == null || a.Article.MetaTag == string.Empty) a.Article.MetaTag = a.Article.Title;
                
                eDataContext.Articles.InsertOnSubmit(a.Article);
                eDataContext.SubmitChanges();

                var eventtid = Request["EventID"] != string.Empty ? Convert.ToInt32(Request["EventID"].ToString()) : 0;
                // Insert table ArticleEventMap
                if (eventtid > 0)
                {
                    var articleEventMap = new ArticleEventMap();
                    articleEventMap.ArticleID = a.Article.ID;
                    articleEventMap.EventID = eventtid;
                    eDataContext.ArticleEventMaps.InsertOnSubmit(articleEventMap);
                }
                
                
                //Image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.ContentLength > 0)
                {
                    a.Article.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}\\{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath), "" + a.Article.ID);
                }
                // Upload attack file
                #region Upload File
                var index = 1;
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    string subPath = string.Format(Settings.Default.ProductFormatSubPath, a.Article.AddDate.Year, a.Article.AddDate.Month, a.Article.AddDate.Day, a.Article.ID);
                    if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                    {
                        var r = new Document();
                        r.AddBy = UserManager.GetUserId();
                        r.AddDate = DateTime.Now;
                        r.ActiveYN = true;
                        r.Name = string.IsNullOrEmpty(Request["fileName" + index]) ? Path.GetFileName(file.FileName) : Request["fileName" + index];
                        r.Path = file.FileName;
                        eDataContext.Documents.InsertOnSubmit(r);
                        eDataContext.SubmitChanges();
                        // Save File 
                        var filePath = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath;
                        Uploads.UploadFile(file,filePath,r.ID.ToString());
                        // Create New DocumentInArticle
                        var docInArticle = new DocumentsInArticle();
                        docInArticle.ArticleID = a.Article.ID;
                        docInArticle.DocumentID = r.ID;
                        eDataContext.DocumentsInArticles.InsertOnSubmit(docInArticle);
                        eDataContext.SubmitChanges();
                        index++;
                    }
                }
                #endregion
                // insert ArticleTagMap    
                var articleTagID = Request["TagID"] != null ? Request["TagID"].ToString() : string.Empty;
                if (articleTagID != string.Empty)
                {
                    var arr = articleTagID.Split(',');
                    if (arr.Length > 0)
                    {
                        for (int i = 0; i < arr.Length; i++)
                        {
                            var itemID = Utils.ParseInt(arr[i]);
                            if (itemID > 0)
                            {
                                ArticleTagMap articleTagMap = new ArticleTagMap();
                                articleTagMap.ArticleID = a.Article.ID;
                                articleTagMap.TagID = itemID;
                                
                                eDataContext.ArticleTagMaps.InsertOnSubmit(articleTagMap);
                                eDataContext.SubmitChanges();
                            }
                        }

                    }
                }



                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch(Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Article/Edit/5
        public ActionResult Edit(int id)
        {
            var currentEventid = eDataContext.ArticleEventMaps.Where(e => e.ArticleID == id).SingleOrDefault();
            
            var currentCompanyid = eDataContext.ArticleCompanyMaps.Where(e => e.ArticleID == id).SingleOrDefault();

            var cp = currentCompanyid == null ? null : eDataContext.Companies.Where(e => e.ID == currentCompanyid.CompanyID).SingleOrDefault();
            var ce = currentEventid == null ? null : eDataContext.Events.Where(e => e.ID == currentEventid.EventID).SingleOrDefault();
            

            var article = eDataContext.Articles.Where(a => a.ID == id).SingleOrDefault();
            var categories = ArticleManager.GetListCategory();
            
            var company = eDataContext.Companies.ToList();
            var events = eDataContext.Events.ToList();
            var listCurrentTag = (from n in eDataContext.ArticleTagMaps where n.ArticleID == id select n.Tag.Keyword).ToList();
            var curentTag = "";
            var listDocument = eDataContext.Documents.ToList();
            var listDocumentID = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).Select(e => e.DocumentID).ToList();
            foreach (var itemtag in listCurrentTag)
            {
                curentTag += itemtag.ToString()+",";        
            }
            return View(new ArticleEditViewModel
            {
                Article = article,
                Categories = categories,
                Companys = company,
                Events = events,                
                CurrentCompany= cp,
                CurrentEvent = ce,                
                ImageRootUrl = Settings.Default.SiteRootUrl+ Settings.Default.ArtileImagePreviewUrlPrefix,
                CurrentListTag = curentTag,
                Documents = listDocument,
                ListDocumentID = listDocumentID,
                FileRootURL = Settings.Default.SiteRootUrl + Settings.Default.DocumentInArticlePreviewUrl

            });
        }
        #endregion

        #region POST: /Article/Edit/5
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(int id, ArticleEditViewModel a)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                // TODO: Add update logic here
                a.Article = eDataContext.Articles.Where(ar => ar.ID == id).SingleOrDefault();
                a.Article.CatID = Request["CatID"] != string.Empty ? Utils.ParseInt(Request["CatID"]) : (int?)null;

                UpdateModel(a);
                if (a.Article.MetaKeyword == null || a.Article.MetaKeyword == string.Empty) a.Article.MetaKeyword = a.Article.Title;
                if (a.Article.MetaDescription == null || a.Article.MetaDescription == string.Empty) a.Article.MetaDescription = a.Article.Title;
                if (a.Article.MetaTag == null || a.Article.MetaTag == string.Empty) a.Article.MetaTag = a.Article.Title;
                
                //image upload
                HttpPostedFileBase fileImage = Request.Files["ArticleImage"];
                if (fileImage != null && fileImage.FileName.Length > 0)
                {
                    //Delete old image
                    if (!string.IsNullOrEmpty(a.Article.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, "" + a.Article.ID + "_" + a.Article.ImagePath)))
                        Uploads.DeleteFile(string.Format("{0}\\{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath, "" + a.Article.ID + "_" + a.Article.ImagePath));

                    //DO upload new image
                    a.Article.ImagePath = Path.GetFileName(fileImage.FileName);
                    Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath), "" + a.Article.ID);
                    
                }                
                eDataContext.SubmitChanges();

                // Delete old map to articles                             
                var ce = eDataContext.ArticleEventMaps.Where(e => e.ArticleID == id);
                if(ce!= null) eDataContext.ArticleEventMaps.DeleteAllOnSubmit(ce);                
                eDataContext.SubmitChanges();

                // Isert new map to article
                var eventtid = Request["EventID"] != string.Empty ? Convert.ToInt32(Request["EventID"].ToString()) : 0;
                
                // Insert table ArticleEventMap
                if (eventtid > 0)
                {
                    var articleEventMap = new ArticleEventMap();
                    articleEventMap.ArticleID = a.Article.ID;
                    articleEventMap.EventID = eventtid;
                    eDataContext.ArticleEventMaps.InsertOnSubmit(articleEventMap);
                }
                
                // Delete old ArticleTagMap
                var listArticleTagMap = eDataContext.ArticleTagMaps.Where(e => e.ArticleID == id).ToList();
                if(listArticleTagMap != null && listArticleTagMap.Count>0) eDataContext.ArticleTagMaps.DeleteAllOnSubmit(listArticleTagMap);
                eDataContext.SubmitChanges();
                // insert ArticleTagMap;
                var stringTagMap = Request["TagName"].ToString();
                if (stringTagMap != null && stringTagMap != string.Empty)
                {
                    foreach (var itemTag in eDataContext.Tags)
                    {
                        if (stringTagMap.Contains(itemTag.Keyword))
                        {
                            var itemArticleTag = new ArticleTagMap();
                            itemArticleTag.ArticleID = id;
                            itemArticleTag.TagID = itemTag.ID;
                            eDataContext.ArticleTagMaps.InsertOnSubmit(itemArticleTag);
                        }
                    }
                }
                #region Upload File
                var index = 1;
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    string subPath = string.Format(Settings.Default.ProductFormatSubPath, a.Article.AddDate.Year, a.Article.AddDate.Month, a.Article.AddDate.Day, a.Article.ID);
                    if (file.ContentLength > 0 && inputTagName != "ArticleImage")
                    {
                        var r = new Document();
                        r.AddBy = UserManager.GetUserId();
                        r.AddDate = DateTime.Now;
                        r.ActiveYN = true;
                        r.Name = string.IsNullOrEmpty(Request["fileName" + index]) ? Path.GetFileName(file.FileName) : Request["fileName" + index];
                        r.Path = file.FileName;
                        eDataContext.Documents.InsertOnSubmit(r);
                        eDataContext.SubmitChanges();
                        // Save File 
                        var filePath = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath;
                        Uploads.UploadFile(file, filePath, r.ID.ToString());
                        // Create New DocumentInArticle
                        var docInArticle = new DocumentsInArticle();
                        docInArticle.ArticleID = a.Article.ID;
                        docInArticle.DocumentID = r.ID;
                        eDataContext.DocumentsInArticles.InsertOnSubmit(docInArticle);
                        eDataContext.SubmitChanges();
                        index++;
                    }
                }
                #endregion

 
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch(Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion       
        
        #region GET: /Article/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    var item = eDataContext.Articles.Single(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Article/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                
                    var item = eDataContext.Articles.Single(e => e.ID == id);
                    if (item != null)
                    {                        
                        Uploads.DeleteFile(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.ArticleImageRootPath,item.ID +"_"+item.ImagePath));
                        // Delete articleCompanyMap
                        var artCompany = eDataContext.ArticleCompanyMaps.Where(e => e.ArticleID == id).ToList();
                        eDataContext.ArticleCompanyMaps.DeleteAllOnSubmit(artCompany);

                        // Delete articleEventMap
                        var artEvent = eDataContext.ArticleEventMaps.Where(e => e.ArticleID == id).ToList();
                        eDataContext.ArticleEventMaps.DeleteAllOnSubmit(artEvent);

                        // Delete articleTagMap
                        var artTag = eDataContext.ArticleTagMaps.Where(e => e.ArticleID == id).ToList();
                        eDataContext.ArticleTagMaps.DeleteAllOnSubmit(artTag);

                        // List Document
                        var listDocument = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).Select(e => e.Document).ToList();
                            // Delete file in folder
                        foreach (var currentDocument in listDocument)
                        {
                            var filePath = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath + currentDocument.ID + "\\"+ currentDocument.Path;
                            Uploads.DeleteFile(filePath);
                        }

                        // Delete Document in article 
                        var documentInArt = eDataContext.DocumentsInArticles.Where(e => e.ArticleID == id).ToList();
                        eDataContext.DocumentsInArticles.DeleteAllOnSubmit(documentInArt);
                        eDataContext.SubmitChanges();

                        // Delete list Document
                        eDataContext.Documents.DeleteAllOnSubmit(listDocument);
                        // Delete current article
                        eDataContext.Articles.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region DeleteFile(int documentID)
        public ActionResult DeleteFile(int id)
        {
            try
            {   
                var currentDocument = eDataContext.Documents.Where(e => e.ID == id).SingleOrDefault();
                // Delete in DocumentInArticles 
                var currentArticleMap = eDataContext.DocumentsInArticles.Where(e => e.DocumentID == id).FirstOrDefault();
                var articleID = currentArticleMap.ArticleID;
                if (currentArticleMap != null)
                    eDataContext.DocumentsInArticles.DeleteOnSubmit(currentArticleMap);
                // Delete File in Hardisk
                var pathFile = Settings.Default.SiteRootPath + Settings.Default.DocumentInArticleRootPath + currentDocument.ID +"_" + currentDocument.Path;
                Uploads.DeleteFile(pathFile);
                // Delete File in table Document
                if (currentDocument != null) eDataContext.Documents.DeleteOnSubmit(currentDocument);
                eDataContext.SubmitChanges();
                return RedirectToAction("Edit/" + articleID);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                throw exp;
            }
            
        }
#endregion
    }
}
